An R Markdown document starts with a header (at the top, between the triple dashes), then alternates between text in Markdown format and chunks of R code.

Markdown is a simple way to add formatting to plain text. You can find more about formatting text using Markdown here: https://bookdown.org/yihui/rmarkdown/markdown-syntax.html

(a) Loading the Tidyverse

Throughout the course, we will be using functions from the tidyverse package. Before you use an R package, you need to load it into your session by calling the library function. It’s a good idea to load all of the packages you need in a single code chunk at the top of your R Markdown file, like this:

library(tidyverse)
── Attaching packages ─────────────────────────────────────── tidyverse 1.3.2 ──
✔ ggplot2 3.4.0      ✔ purrr   0.3.5 
✔ tibble  3.1.8      ✔ dplyr   1.0.10
✔ tidyr   1.2.1      ✔ stringr 1.5.0 
✔ readr   2.1.3      ✔ forcats 0.5.2 
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()

You can insert new code chunks either by typing in the triple backticks and curly braces by hand, using the Insert > R button in RStudio, or pressing Control-Alt-I. (The keyboard shortcut won’t work on University owned machines due to software installed by central IT.)

You can run a code chunk by pressing the green “play” button on the right of the chunk, or pressing Ctrl-Shift-Enter when the cursor is in the chunk. There are more options for running code in the Run button above and to the right of the code editor.

Code chunks can have a name (like packages above) or they can be unnamed (like the one below). Code chunks can also have options - for example, the setup chunk at the top of this file has an option include = FALSE which prevents it from showing up in the knitted document.

(b) Using R as a calculator

One of the simplest things R can do is numerical calculations. For example, this code -

24 * 60 * 60
[1] 86400

will calculate the number of seconds in a day.

(c) Getting to know RStudio

Try knitting this document using the Knit button above, or pressing Control-Shift-K.

Manually run the code chunks above using the green “play” button in RStudio.

Type a mathematical expression in the R console (below the code editor) and see what happens. In the R console, the Up and Down arrow keys go backwards and forwards through your command history - useful for recalling and modifying something you just typed.

Have a look at the Help > Keyboard Shortcuts menu.


© 2021 Statistical Consulting Centre, The University of Melbourne.